<script setup>
import {
    Flag
} from '@element-plus/icons-vue'
import { Icon } from '@iconify/vue';
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus'

const loading1 = ref(false)
const loading2 = ref(false)

// 用户搜索时选中的分类id
const chartContainer1 = ref(null); // 折线图容器
const chartContainer2 = ref(null); // 柱状图容器
const chartContainer3 = ref(null); // 饼状图容器1
const chartContainer4 = ref(null); // 饼状图容器2

//定义数据模型
const RegionData = ref({
    name: '东城区',
    loadName: '商业区',
    data: '2023-01-01',
})
const regiondata = ref({
    name: '',
    loadName: '',
    data: ''
});
const regiondata_no_load_name = ref({
    name: '',
    data: ''
})

//地区名字汇总
const names = ref([]);
//搜索结果汇总
const SearchInfoValue = ref([]);

const fire = Array(24).fill(100);
const water = Array(24).fill(200);
const wind = Array(24).fill(300);
const solar = Array(24).fill(400);
const nuclear = Array(24).fill(500);

// 初始化 ECharts 图表实例
let chartInstance1 = null; // 折线图实例
let chartInstance2 = null; // 柱状图实例
let chartInstance3 = null;
let chartInstance4 = null;

// 初始曲线图逻辑
const initChart1 = () => {
    if (chartContainer1.value) {
        chartInstance1 = echarts.init(chartContainer1.value);

        const option = {
            title: {
                text: '电力来源24h曲线图'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['火力发电', '水力发电', '风力发电', '太阳能发电', '核能发电']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: ['00:00', '00:01', '00:02', '00:03', '00:04', '00:05',
                    '00:06', '00:07', '00:08', '00:09', '00:10', '00:11',
                    '00:12', '00:13', '00:14', '00:15', '00:16', '00:17',
                    '00:18', '00:19', '00:20', '00:21', '00:22', '00:23']
            },
            yAxis: {
                type: 'value',
            },
            series: [
                {
                    name: '火力发电',
                    type: 'line',
                    data: fire,
                    smooth: true
                },
                {
                    name: '水力发电',
                    type: 'line',
                    data: water,
                    smooth: true
                },
                {
                    name: '风力发电',
                    type: 'line',
                    data: wind,
                    smooth: true
                },
                {
                    name: '太阳能发电',
                    type: 'line',
                    data: solar,
                    smooth: true
                },
                {
                    name: '核能发电',
                    type: 'line',
                    data: nuclear,
                    smooth: true
                }
            ]
        };

        chartInstance1.setOption(option);
    }
};

// 初始化柱状图逻辑
const initChart2 = () => {
    if (chartContainer2.value) {
        chartInstance2 = echarts.init(chartContainer2.value);

        const option = {
            title: {
                text: '当日各分区电力来源柱状图'
            },
            legend: {
                selected: {
                    '发电总量': false
                }
            },
            tooltip: {
            },
            dataset: {
                dimensions: ['product', '火力发电', '水力发电', '风力发电', '太阳能发电', '核能发电', '发电总量'],
                source: [
                    { product: '商业区', 火力发电: 100, 水力发电: 110, 风力发电: 120, 太阳能发电: 130, 核能发电: 140, 发电总量: 800 },
                    { product: '工业区', 火力发电: 100, 水力发电: 110, 风力发电: 120, 太阳能发电: 130, 核能发电: 140, 发电总量: 800 },
                    { product: '居民区', 火力发电: 100, 水力发电: 110, 风力发电: 120, 太阳能发电: 130, 核能发电: 140, 发电总量: 800 },
                    { product: '行政区', 火力发电: 100, 水力发电: 110, 风力发电: 120, 太阳能发电: 130, 核能发电: 140, 发电总量: 800 }
                ]
            },
            xAxis: { type: 'category' },
            yAxis: {},
            series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }, { type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
        };

        chartInstance2.setOption(option);
    }
};
// 初始化饼状图逻辑
const initChart3 = () => {
    if (chartContainer3.value) {
        chartInstance3 = echarts.init(chartContainer3.value);

        const option = {
            title: {
                text: '2023年各月份用电总量饼状图'
            },
            legend: {
                top: 'bottom'
            },
            tooltip: {  // 添加 tooltip 配置
                trigger: 'item',
                formatter: '{b}: {c} kw·h  占({d}%)'  // 显示月份、数值和百分比
            },
            toolbox: {
                show: true,
                feature: {
                }
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 10, name: '1月' },
                        { value: 12, name: '2月' },
                        { value: 14, name: '3月' },
                        { value: 16, name: '4月' },
                        { value: 18, name: '5月' },
                        { value: 20, name: '6月' },
                        { value: 22, name: '7月' },
                        { value: 24, name: '8月' },
                        { value: 26, name: '9月' },
                        { value: 28, name: '10月' },
                        { value: 30, name: '11月' },
                        { value: 32, name: '12月' },
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }

        chartInstance3.setOption(option);
    }
}

// 初始化饼状图逻辑
const initChart4 = () => {
    if (chartContainer4.value) {
        chartInstance4 = echarts.init(chartContainer4.value);

        const option = {
            title: {
                text: '2024年各月份用电总量饼状图'
            },
            legend: {
                top: 'bottom'
            },
            tooltip: {  // 添加 tooltip 配置
                trigger: 'item',
                formatter: '{b}: {c} kw·h  占({d}%)'  // 显示月份、数值和百分比
            },
            toolbox: {
                show: true,
                feature: {
                }
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 10, name: '1月' },
                        { value: 12, name: '2月' },
                        { value: 14, name: '3月' },
                        { value: 16, name: '4月' },
                        { value: 18, name: '5月' },
                        { value: 20, name: '6月' },
                        { value: 22, name: '7月' },
                        { value: 24, name: '8月' },
                        { value: 26, name: '9月' },
                        { value: 28, name: '10月' },
                        { value: 30, name: '11月' },
                        { value: 32, name: '12月' },
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }

        chartInstance4.setOption(option);
    }
}


// 窗口大小调整时重绘图表
const resizeCharts = () => {
    if (chartInstance1) {
        chartInstance1.resize();
    }
    if (chartInstance2) {
        chartInstance2.resize();
    }
};

//搜索框
import { FindAllNameService, SearchInfo, TotalRegion, TotalElectric, AvgTemperature, SearchInfo_no_load_name, monthly_power_2023, monthly_power_2024 } from '@/api/electric.js'

//获取所有地区列表 
const List = async () => {
    try {
        let result = await FindAllNameService();
        if (!result || !Array.isArray(result)) {
            throw new Error('Invalid data format from API');
        }
        names.value = result;
    } catch (error) {
        console.error('Error fetching names:', error);
        ElMessage.error('无法加载地区分类，请稍后重试');
    }
};

// 重置按钮
const reback = () => {
    RegionData.value.name = '东城区';
    RegionData.value.loadName = '商业区';
    RegionData.value.data = '2023-01-01';
};

const target1 = ref(0);
const target2 = ref(0);
const target3 = ref(0);

//搜索按钮
const search = async () => {
    loading1.value = true;
    loading2.value = true;
    // 检查name data 是否为空
    if (!RegionData.value.name || !RegionData.value.loadName || !RegionData.value.data) {
        ElMessage.warning('请填写用需要查询到地区和时间');
        return;
    }

    regiondata.value.name = RegionData.value.name;
    regiondata_no_load_name.value.name = RegionData.value.name;

    // 格式化子区分类的输出
    switch (RegionData.value.loadName) {
        case '商业区':
            regiondata.value.loadName = 1;
            break;
        case '工业区':
            regiondata.value.loadName = 2;
            break;
        case '居民区':
            regiondata.value.loadName = 3;
            break;
        case '行政区':
            regiondata.value.loadName = 4;
            break;
    }

    // 使用本地时间格式化日期，避免 toISOString 的时区偏移
    const selectedDate = new Date(RegionData.value.data);
    const year = selectedDate.getFullYear();
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const day = String(selectedDate.getDate()).padStart(2, '0');
    RegionData.value.data = `${year}-${month}-${day}`;

    if (year !== 2023 && year !== 2024) {
        ElMessage.warning('请选择2023年或2024年的日期');
        return;
    }

    regiondata.value.data = RegionData.value.data;
    regiondata_no_load_name.value.data = RegionData.value.data;

    console.log(regiondata_no_load_name.value)

    try {
        let result1 = await SearchInfo(regiondata.value);
        let result2 = await AvgTemperature(regiondata.value);
        let result3 = await TotalElectric(regiondata.value);
        let result4 = await SearchInfo_no_load_name(regiondata_no_load_name.value);
        let result5 = await monthly_power_2023();
        let result6 = await monthly_power_2024();
        SearchInfoValue.value = result1;
        target1.value = result2;
        target2.value = result3;
        animateNumber(displayNumber2, 0, target2.value, 1000);
        animateNumber(displayNumber1, 0, target1.value, 1000);

        const result4Array = Array.from(result4);
        const result5Array = Array.from(result5);
        const result6Array = Array.from(result6);

        //得到曲线图数据
        for (const item of SearchInfoValue.value) {
            const hourIndex = item.recordHour;
            switch (item.resource) {
                case 1:
                    fire[hourIndex] = item.powerConsumption;
                    break;
                case 2:
                    water[hourIndex] = item.powerConsumption;
                    break;
                case 3:
                    wind[hourIndex] = item.powerConsumption;
                    break;
                case 4:
                    solar[hourIndex] = item.powerConsumption;
                    break;
                case 5:
                    nuclear[hourIndex] = item.powerConsumption;
                    break;
            }
        }

        // 更新折线图数据
        if (chartInstance1) {
            chartInstance1.setOption({
                series: [
                    { name: '火力发电', data: fire },
                    { name: '水力发电', data: water },
                    { name: '风力发电', data: wind },
                    { name: '太阳能发电', data: solar },
                    { name: '核能发电', data: nuclear }
                ]
            });
        }

        //更新柱状图数据
        if (chartInstance2) {
            chartInstance2.setOption({
                dataset: {
                    dimensions: ['product', '火力发电', '水力发电', '风力发电', '太阳能发电', '核能发电', '发电总量'],
                    source: [
                        { product: '商业区', 火力发电: result4Array[0].toFixed(2), 水力发电: result4Array[1].toFixed(2), 风力发电: result4Array[2].toFixed(2), 太阳能发电: result4Array[3].toFixed(2), 核能发电: result4Array[4].toFixed(2), 发电总量: result4Array[20].toFixed(2) },
                        { product: '工业区', 火力发电: result4Array[5].toFixed(2), 水力发电: result4Array[6].toFixed(2), 风力发电: result4Array[7].toFixed(2), 太阳能发电: result4Array[8].toFixed(2), 核能发电: result4Array[9].toFixed(2), 发电总量: result4Array[21].toFixed(2) },
                        { product: '居民区', 火力发电: result4Array[10].toFixed(2), 水力发电: result4Array[11].toFixed(2), 风力发电: result4Array[12].toFixed(2), 太阳能发电: result4Array[13].toFixed(2), 核能发电: result4Array[14].toFixed(2), 发电总量: result4Array[22].toFixed(2) },
                        { product: '行政区', 火力发电: result4Array[15].toFixed(2), 水力发电: result4Array[16].toFixed(2), 风力发电: result4Array[17].toFixed(2), 太阳能发电: result4Array[18].toFixed(2), 核能发电: result4Array[19].toFixed(2), 发电总量: result4Array[23].toFixed(2) },
                    ]
                },
            });
        }

        loading1.value = false;
        loading2.value = false;

        //更新饼状图数据1
        if (chartInstance3) {
            chartInstance3.setOption({
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: '50%',
                        data: [
                            { value: result5Array[0], name: '1月' },
                            { value: result5Array[1], name: '2月' },
                            { value: result5Array[2], name: '3月' },
                            { value: result5Array[3], name: '4月' },
                            { value: result5Array[4], name: '5月' },
                            { value: result5Array[5], name: '6月' },
                            { value: result5Array[6], name: '7月' },
                            { value: result5Array[7], name: '8月' },
                            { value: result5Array[8], name: '9月' },
                            { value: result5Array[9], name: '10月' },
                            { value: result5Array[10], name: '11月' },
                            { value: result5Array[11], name: '12月' },
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            });
        }

        //更新饼状图数据2
        if (chartInstance4) {
            chartInstance4.setOption({
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: '50%',
                        data: [
                            { value: result6Array[0], name: '1月' },
                            { value: result6Array[1], name: '2月' },
                            { value: result6Array[2], name: '3月' },
                            { value: result6Array[3], name: '4月' },
                            { value: result6Array[4], name: '5月' },
                            { value: result6Array[5], name: '6月' },
                            { value: result6Array[6], name: '7月' },
                            { value: result6Array[7], name: '8月' },
                            { value: result6Array[8], name: '9月' },
                            { value: result6Array[9], name: '10月' },
                            { value: result6Array[10], name: '11月' },
                            { value: result6Array[11], name: '12月' },
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            });
        }

        ElMessage.success('查询数据成功！')

    } catch (error) {
        console.error('Error fetching names:', error);
        ElMessage.error('错误请稍后重试');
    }
}

//获取城市总数
const getAllRegionCount = async () => {
    try {
        let result = await TotalRegion();
        target3.value = result;
    } catch {
        ElMessage.error("获取城市总数失败！")
    }
}

//数字滚动js
const displayNumber1 = ref(0)
const displayNumber2 = ref(0)
const displayNumber3 = ref(0)
function animateNumber(displayRef, start, end, duration = 1000, decimalPlaces = 2) {
    const startTime = performance.now();

    function update(currentTime) {
        const progress = Math.min((currentTime - startTime) / duration, 1);
        const value = progress * (end - start) + start;
        displayRef.value = parseFloat(value.toFixed(decimalPlaces));
        if (progress < 1) {
            requestAnimationFrame(update);
        }
    }
    requestAnimationFrame(update);
}


// 使用生命周期钩子
onMounted(async () => {
    await List();
    await getAllRegionCount();
    animateNumber(displayNumber1, 0, 24, 1000, 0)
    animateNumber(displayNumber2, 0, 300.00, 1000, 2)
    animateNumber(displayNumber3, 0, target3.value, 1000, 0)
    initChart1();
    initChart2();
    initChart3();
    initChart4();
    window.addEventListener('resize', resizeCharts);
});
</script>

<template>
    <el-card>
        <template #header>
            <div class="header">
                <Icon icon="noto:chart-increasing" width="38" height="38" />
                <span style="font-size: 28px;"><strong>&nbsp;详细数据展示</strong></span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form :model="RegionData" inline>
            <div class="search">
                <div>
                    <el-form-item label="地区分类：">
                        <el-select placeholder="请选择地区" v-model="RegionData.name">
                            <el-option v-for="c in names" :key="c.regionName" :label="c.regionName"
                                :value="c.regionName">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="子区分类：">
                        <el-select placeholder="请选择子区" v-model="RegionData.loadName">
                            <el-option label="商业区" value="商业区"></el-option>
                            <el-option label="工业区" value="工业区"></el-option>
                            <el-option label="居民区" value="居民区"></el-option>
                            <el-option label="行政区" value="行政区"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="选择日期：">
                        <el-date-picker v-model="RegionData.data" type="date" placeholder="请选择需要分析的日期" :size="size" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="search">搜索</el-button>
                        <el-button @click="reback">重置</el-button>
                    </el-form-item>
                    <el-icon>
                        <Flag />
                    </el-icon>
                    <span style="font-size: 14px;"> &nbsp;请注意: 时间只能选择在 2023-01-01 至 2024-12-31 之间</span>

                </div>
                <div>
                    <el-card style="width: 365px;height: 65px;" shadow="hover">
                        <strong style="font-size: 20px;">&nbsp;城市总数:&nbsp;&nbsp;&nbsp;{{ displayNumber3 }}</strong>
                    </el-card>
                </div>
            </div>
        </el-form>

        <div class="main-content">
            <!-- 左侧卡片区 -->
            <div class="card-column">
                <el-card
                    style="width: 250px;height: 200px;margin-top: 10px;display: flex; flex-direction: column; justify-content: center; align-items: center;"
                    shadow="hover">
                    <template #header><strong style="font-size: 20px;">&nbsp;当日天气平均气温℃</strong></template>
                    <div style="text-align: center;">
                        <strong style="font-size: 30px;">{{
                            displayNumber1
                        }}&nbsp;℃</strong>
                    </div>
                </el-card>
                <el-card
                    style="width: 250px;height: 200px;margin-bottom: 10px;display: flex; flex-direction: column; justify-content: center; align-items: center;"
                    shadow="hover">
                    <template #header><strong style="font-size: 20px;">&nbsp;本日用电量 单位：千瓦时（kw·h）</strong></template>
                    <div style="text-align: center;">
                        <strong style="font-size: 27px;">{{
                            displayNumber2
                        }}&nbsp;kw·h</strong>
                    </div>
                </el-card>
            </div>
            <!-- 右侧图表区 -->
            <div class="chart-area" v-loading="loading1">
                <el-card shadow="hover">
                    <div>
                        <!-- 折线图 -->
                        <div ref="chartContainer1" style="width: 100%; height: 400px; margin-bottom: 20px;"></div>
                    </div>
                </el-card>
            </div>
        </div>
        <div style="width: 100%;margin-top: 20px;">
            <el-card shadow="hover" v-loading="loading2">
                <!-- 柱状图 -->
                <div ref="chartContainer2" style="width: 100%; height: 400px;">
                </div>
            </el-card>
        </div>
        <div style="display: flex;">
            <div style="width: 50%;margin-top: 20px;">
                <el-card shadow="hover">
                    <!-- 饼状图 -->
                    <div ref="chartContainer3" style="width: 100%; height: 400px;">
                    </div>
                </el-card>
            </div>
            <div style="width: 50%;margin-top: 20px;">
                <el-card shadow="hover">
                    <!-- 饼状图 -->
                    <div ref="chartContainer4" style="width: 100%; height: 400px;">
                    </div>
                </el-card>
            </div>
        </div>


    </el-card>

</template>

<style lang="scss" scoped>
.search {
    display: flex;
}

.main-content {
    display: flex;
    margin-top: 20px;
}

.card-column {
    display: flex;
    flex-direction: column;
    gap: 38px;
    /* 控制上下间距 */
    width: 260px;
    margin-right: 20px;
    /* 卡片和图表间距 */
}

.info-card {
    height: 200px;
}

.chart-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.chart {
    width: 100%;
    height: 400px;
}


.main-content {
    display: flex;
    margin-top: 20px;
}

.el-select {
    width: 150px;
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}

.primary {
    margin-top: 100px;
}
</style>